package com.xxl.job.executor.tasks;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxl.job.common.utils.MD5Utils;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.entity.SroUserInfo;
import com.xxl.job.executor.entity.TbUser;
import com.xxl.job.executor.service.ISroUserInfoService;
import com.xxl.job.executor.service.ITbUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class DataSyncScheduledTask {

    private static final Logger logger = LogManager.getLogger(DataSyncScheduledTask.class);

    @Resource
    private ISroUserInfoService sroUserInfoService;

    @Resource
    private ITbUserService tbUserService;

    /**
     * 定时同步账号到sqlserver数据库
     */
    @XxlJob("UserJobHandler")
    public void UserJobHandler() {
        try {
            List<SroUserInfo> list = sroUserInfoService.getList();
            TbUser user = new TbUser();
            for (SroUserInfo sroUserInfo : list) {
                user.setStruserid(sroUserInfo.getAccount());
                user.setPassword(MD5Utils.string2MD5(sroUserInfo.getPassword()));
                user.setEmail(sroUserInfo.getEmail());
                user.setGmrank(sroUserInfo.getGmrank());
                user.setCertificateNum(sroUserInfo.getCertificateNum());
                boolean isSave = false;
                // 新增数据同步逻辑
                if (sroUserInfo.getStatusCode() == 1) {
                    isSave = tbUserService.insertUser(user);
                }
                // 修改数据同步逻辑
                if (sroUserInfo.getStatusCode() == 2) {
                    LambdaUpdateWrapper<TbUser> updateTbUserWrapper = new LambdaUpdateWrapper<>();
                    updateTbUserWrapper.set(TbUser::getPassword,MD5Utils.string2MD5(sroUserInfo.getPassword()))
                            .set(TbUser::getEmail,sroUserInfo.getEmail())
                            .eq(TbUser::getStruserid,sroUserInfo.getAccount());
                    isSave = tbUserService.update(updateTbUserWrapper);
                }
                // 同步成功 修改数据状态
                if (isSave) {
                    LambdaUpdateWrapper<SroUserInfo> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(SroUserInfo::getAccount,sroUserInfo.getAccount())
                            .set(SroUserInfo::getStatusCode,0);
                    sroUserInfoService.update(updateWrapper);
                }
            }
            logger.info("账号成功同步: [" + list.size() + "]条!");
        } catch (Exception e) {
            logger.error("数据同步出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}